﻿using ChongJu.EventManager;
using ChongJu.GlobalInfo;
using Public.Logger;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChoJu.Single.DAL
{
    public class SerWeightDal
    {
        private SerialPort serialPort = null;
        //回应数据
        private byte[] byResponse = new byte[32];


        public bool Init()
        {
            try
            {
                serialPort = new SerialPort();

                //设置参数

                serialPort.PortName = "COM3"; //通信端口
                serialPort.BaudRate = 9600; //串行波特率
                serialPort.DataBits = 8; //每个字节的标准数据位长度
                serialPort.StopBits = StopBits.One; //设置每个字节的标准停止位数
                serialPort.Parity = Parity.None; //设置奇偶校验检查协议
                serialPort.ReadTimeout = 3000; //单位毫秒
                serialPort.WriteTimeout = 3000; //单位毫秒
                                                //串口控件成员变量，字面意思为接收字节阀值，
                                                //串口对象在收到这样长度的数据之后会触发事件处理函数
                                                //一般都设为1
                serialPort.ReceivedBytesThreshold = 1;
                serialPort.DataReceived += new SerialDataReceivedEventHandler(CommDataReceived); //设置数据接收事件（监听）

                serialPort.Open(); //打开串口
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error("初始化后端称异常", ex);
                return false;
            }
        }

        private void CommDataReceived(Object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                Thread.Sleep(20); //延时10ms 

                //Comm.BytesToRead中为要读入的字节长度
                int len = serialPort.BytesToRead;
                byte[] arr = new byte[32];
                serialPort.Read(arr, 0, arr.Length); //将数据读入缓存
                byResponse = arr;
                
            }
            catch (Exception ex)
            {
                Logger.Error("称重回调异常", ex);
            }
        }

        public void Read()
        {
            var arr = new List<byte>() { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xc4, 0x0b }.ToArray();
            serialPort.Write(arr, 0, arr.Length);
        }
    }
}
